package com.blockmeta.bbs.immodule.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;

import com.blankj.utilcode.util.LogUtils;

import android.view.View;
import android.widget.Button;

import com.blockmeta.bbs.baselibrary.net.callback.Callback;
import com.blockmeta.bbs.baselibrary.net.callback.FileUploadCallBack;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.net.okhttp.OKHttpGetReq;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseImResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.Update2QiniuCloud;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.bean.Params;
import com.blockmeta.bbs.immodule.corebean.IFileHttpService;
import com.blockmeta.bbs.immodule.corebean.IMMetaBase;
import com.blockmeta.bbs.immodule.corebean.Impl.FileHttpService;
import com.blockmeta.bbs.immodule.corebean.Impl.IMApplicationContext;
import com.blockmeta.bbs.immodule.net.api.UpdateCircleApi;
import com.blockmeta.bbs.immodule.net.pojo.CircleDetailResponse;
import com.blockmeta.bbs.immodule.widget.LengthLimitEditText;
import com.blockmeta.bbs.immodule.widget.MyBottomPopupWindow;

import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;

import com.zhy.http.okhttp.OkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author airthor
 * @date 2019/2/19
 * 创建圈子之基本资料
 */
public class EditGroupInfoActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R2.id.iv_upload_avatar)
    CircleImageView mIvUploadAvatar;
    @BindView(R2.id.edt_circle_name)
    LengthLimitEditText mEdtCircleName;
    @BindView(R2.id.edt_circle_info)
    LengthLimitEditText mEdtCircleInfo;
    @BindView(R2.id.btn_save)
    Button mSave;


    private MyBottomPopupWindow popupWindow;
    private HashMap<String, String> params = new HashMap<>();

    public static EditGroupInfoActivity Instance = null;
    private CircleDetailResponse mCircleDetailResponse;
    private IFileHttpService mFileHttpService;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        return getLayoutInflater().inflate(R.layout.activity_edit_group_info, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        mFileHttpService = new FileHttpService(this);
        mCircleDetailResponse = getIntent().getParcelableExtra(Params.CIRCLE_DETAIL);
        bindCircleData();
    }

    private void bindCircleData() {
        LoadPicUtil.loadWithPicasso(mIvUploadAvatar, mCircleDetailResponse.groupLogo);
        mEdtCircleName.setText(mCircleDetailResponse.name);
        mEdtCircleInfo.setText(mCircleDetailResponse.description);
    }


    @OnClick({R2.id.fl_back, R2.id.fl_next, R2.id.iv_upload_avatar, R2.id.btn_save})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.fl_back) {
            finish();

        } else if (i == R.id.iv_upload_avatar) {//选择头像
            showIconChoice();

        } else if (i == R.id.btn_save) {
            updateCircleInfo();

        } else {
        }
    }

    private void updateCircleInfo() {
        ProgressBarUtil.showProgress(mContext);
        params.put("chatGroupId", String.valueOf(mCircleDetailResponse.id));
        params.put("userId", String.valueOf(AccountHelper.getUidInt()));
        params.put("name", mEdtCircleName.getText().toString().trim());
        params.put("desc", mEdtCircleInfo.getText().toString().trim());


        RetrofitFactory.getRetrofit().create(UpdateCircleApi.class)
                .updateChatGroup(params)
                .compose(RxUtil.<BaseImResponse<CircleDetailResponse>>rxSchedulerHelper())
                .compose(RxUtil.<CircleDetailResponse>commonResult())
                .compose(this.<CircleDetailResponse>bindToLifecycle())
                .subscribe(new CommonSubscriber<CircleDetailResponse>(mContext) {
                    @Override
                    public void onNext(CircleDetailResponse circleDetailResponse) {
                        IMApplicationContext.getCircleDomainService()
                                .updateCircleInfo(mCircleDetailResponse.id
                                        , AccountHelper.getUidInt(), params.get("name"), params.get("desc"));
                        //关闭此页面
                        IMApplicationContext.getIMMetaService().post(new IMMetaBase.Event_EditCircles(mCircleDetailResponse.id));
                        finish();
                    }
                });
    }


    private void showIconChoice() {
        popupWindow = new MyBottomPopupWindow(mContext);
        popupWindow.tx2.setText("相册");
        popupWindow.tx3.setText("拍照");
        popupWindow.tx2.setOnClickListener(this);
        popupWindow.tx3.setOnClickListener(this);
        popupWindow.tx4.setOnClickListener(this);

        popupWindow.showPopupWindow();

    }

    @Override
    public void onClick(View v) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        int i = v.getId();
        if (i == R.id.popup_tx_2) {//相册
            getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());

        } else if (i == R.id.popup_tx_3) {//拍照
            getTakePhoto().onPickFromCaptureWithCrop(imageUri, getCropOptions());

        } else if (i == R.id.popup_tx_4) {//取消
            popupWindow.dismiss();

        } else {
        }
    }

    //裁剪
    private CropOptions getCropOptions() {
        int height = Integer.parseInt("150");
        int width = Integer.parseInt("150");
        //TokePhoto裁剪工具
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setOutputX(width).setOutputY(height);
        builder.setWithOwnCrop(true);
        return builder.create();
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        TImage image = result.getImage();
        String compressPath = image.getOriginalPath();
        Bitmap bitmap = BitmapFactory.decodeFile(compressPath);
        mIvUploadAvatar.setImageBitmap(bitmap);
        postIconToNet(compressPath);
        popupWindow.dismiss();

    }

    private void postIconToNet(final String compressPath) {
        try {
            ProgressBarUtil.showProgress(mContext);
            mFileHttpService.uploadImImage(this, compressPath, new IFileHttpService.IMFileUploadCallBack() {
                @Override
                public void fail(String msg) {
                    ProgressBarUtil.dismissProgress(mContext);
                    ToastUtil.show("上传失败，请稍后重试");
                }

                @Override
                public void progress(int progress) {
                }

                @Override
                public void success(String fileUrl, String fileName, String fileParam) {
                    //获取到传输成功之后七牛云存储地址！
                    params.put("logo", fileUrl);
                    ProgressBarUtil.dismissProgress(mContext);
                }
            });
        } catch (Exception e) {
            LogUtils.d("uploadimage error " + e.getMessage());
        }


    }


    @Override
    protected void onDestroy() {
        Instance = null;
        super.onDestroy();
    }
}
